import React, { useState, useEffect } from "react";

// 导入共享组件
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Plus, Trash2, RefreshCw } from "lucide-react";

const EngineeringFactors = ({ factors = {}, onUpdate }) => {
  // 获取默认系数配置
  const getDefaultFactors = () => ({
    spanFactorRules: [
      { threshold: 500, multiplier: 1.5 },
      { threshold: 300, multiplier: 1.2 },
      { threshold: 150, multiplier: 1.0 },
      { threshold: 0, multiplier: 0.8 },
    ],
    heightFactorRules: [
      { threshold: 80, multiplier: 1.4 },
      { threshold: 50, multiplier: 1.2 },
      { threshold: 30, multiplier: 1.0 },
      { threshold: 0, multiplier: 0.9 },
    ],
    nettingFactorRules: [
      { threshold: 200, multiplier: 2.0 },
      { threshold: 150, multiplier: 1.5 },
      { threshold: 100, multiplier: 1.0 },
      { threshold: 50, multiplier: 0.8 },
      { threshold: 0, multiplier: 0.5 },
    ],
    angleFactorRules: [
      { threshold: 60, multiplier: 1.3 },
      { threshold: 75, multiplier: 1.1 },
      { threshold: 90, multiplier: 1.0 },
    ],
    widthFactorRules: [
      { threshold: 50, multiplier: 1.4 },
      { threshold: 20, multiplier: 1.2 },
      { threshold: 10, multiplier: 1.0 },
      { threshold: 0, multiplier: 0.8 },
    ],
    typeFactorMultipliers: [
      { type: "highwayExpressway", multiplier: 1.5 },
      { type: "highwayGradePlus2", multiplier: 1.3 },
      { type: "railwayHighSpeed", multiplier: 1.6 },
      { type: "railwayNormal", multiplier: 1.4 },
      { type: "riverNavigable", multiplier: 1.2 },
      { type: "powerLineOutagePlus500", multiplier: 1.8 },
      { type: "powerLineOutagePlus110", multiplier: 1.7 },
      { type: "powerLineOutagePlus10", multiplier: 1.6 },
      { type: "other", multiplier: 1.0 },
    ],
  });

  const [currentFactors, setCurrentFactors] = useState({});

  // 初始化或从props更新系数
  useEffect(() => {
    const defaultFactors = getDefaultFactors();
    const mergedFactors = {};
    let isInitialLoadWithEmptyFactors = true;

    Object.keys(defaultFactors).forEach((key) => {
      if (
        factors &&
        factors[key] &&
        Array.isArray(factors[key]) &&
        factors[key].length > 0
      ) {
        mergedFactors[key] = factors[key];
        isInitialLoadWithEmptyFactors = false;
      } else {
        mergedFactors[key] = defaultFactors[key];
      }
    });

    setCurrentFactors(mergedFactors);

    // 如果是首次加载且传入的factors为空或无效，则立即用默认值更新父组件
    if (isInitialLoadWithEmptyFactors) {
      onUpdate(mergedFactors);
    }
  }, [factors, onUpdate]);

  // 更新因子规则
  const updateFactorRule = (category, index, field, value) => {
    const newFactors = { ...currentFactors };
    if (!newFactors[category]) {
      newFactors[category] = [];
    }

    const newRules = [...newFactors[category]];
    if (field === "threshold" || field === "multiplier") {
      newRules[index] = { ...newRules[index], [field]: parseFloat(value) || 0 };
    } else {
      newRules[index] = { ...newRules[index], [field]: value };
    }

    newFactors[category] = newRules;
    setCurrentFactors(newFactors);
    onUpdate(newFactors);
  };

  // 添加新的因子规则
  const addFactorRule = (category) => {
    const newFactors = { ...currentFactors };
    if (!newFactors[category]) {
      newFactors[category] = [];
    }

    const newRule =
      category === "typeFactorMultipliers"
        ? { type: "", multiplier: 1.0 }
        : { threshold: 0, multiplier: 1.0 };

    newFactors[category] = [...newFactors[category], newRule];
    setCurrentFactors(newFactors);
    onUpdate(newFactors);
  };

  // 删除因子规则
  const removeFactorRule = (category, index) => {
    const newFactors = { ...currentFactors };
    if (newFactors[category] && newFactors[category].length > 1) {
      newFactors[category] = newFactors[category].filter((_, i) => i !== index);
      setCurrentFactors(newFactors);
      onUpdate(newFactors);
    }
  };

  // 重置为默认值
  const resetToDefaults = () => {
    const defaultFactors = getDefaultFactors();
    setCurrentFactors(defaultFactors);
    onUpdate(defaultFactors);
  };

  // 因子规则编辑器组件
  const FactorRuleEditor = ({
    title,
    category,
    rules,
    isTypeRule = false,
    description,
  }) => (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <div className="flex items-center justify-between">
        <div>
          <h4 className="font-medium text-gray-800">{title}</h4>
          <p className="text-sm text-gray-600 mt-1">{description}</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => addFactorRule(category)}
          className="bg-white"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加规则
        </Button>
      </div>

      <div className="space-y-2">
        {rules &&
          rules.map((rule, index) => (
            <div
              key={index}
              className="flex items-center gap-2 p-2 bg-white rounded border"
            >
              {isTypeRule ? (
                <>
                  <select
                    value={rule.type || ""}
                    onChange={(e) =>
                      updateFactorRule(category, index, "type", e.target.value)
                    }
                    className="flex-1 px-2 py-1 border rounded text-sm h-9"
                  >
                    <option value="">选择类型</option>
                    <option value="powerLineOutagePlus500">
                      跨越电力线路（带电）
                    </option>
                    <option value="powerLineOutagePlus110">
                      跨越电力线路（不带电）
                    </option>
                    <option value="railway">跨越普通铁路</option>
                    <option value="railwayHighSpeed">跨越高铁</option>
                    <option value="firstHighway">
                      跨越高速公路(含全封闭一级公路)
                    </option>
                    <option value="highwayGradePlus2">
                      跨越公路(二级及以下公路)
                    </option>
                    <option value="navigableRivers">跨越通航河流</option>
                    <option value="noNavigableRivers">跨越不通航河流</option>
                    <option value="railwayNormal">跨越通信线路</option>
                    <option value="other">其它</option>
                  </select>
                  <span className="text-sm text-gray-500 whitespace-nowrap">
                    系数:
                  </span>
                </>
              ) : (
                <>
                  <span className="text-sm text-gray-500 whitespace-nowrap">
                    {category.includes("angle") ? "< " : "≥ "}
                  </span>
                  <Input
                    type="number"
                    step="0.1"
                    value={rule.threshold || 0}
                    onChange={(e) =>
                      updateFactorRule(
                        category,
                        index,
                        "threshold",
                        e.target.value
                      )
                    }
                    className="w-24 text-sm"
                    placeholder="阈值"
                  />
                  <span className="text-sm text-gray-500">系数:</span>
                </>
              )}
              <Input
                type="number"
                step="0.1"
                value={rule.multiplier || 1.0}
                onChange={(e) =>
                  updateFactorRule(
                    category,
                    index,
                    "multiplier",
                    e.target.value
                  )
                }
                className="w-20 text-sm"
                placeholder="1.0"
              />
              <Button
                variant="ghost"
                size="icon"
                onClick={() => removeFactorRule(category, index)}
                className="text-red-500 hover:text-red-700 shrink-0"
                disabled={rules.length <= 1}
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          ))}
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">工程系数规则配置</h3>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={resetToDefaults}
          className="bg-blue-50 border-blue-200 text-blue-700 hover:bg-blue-100"
        >
          <RefreshCw className="w-4 h-4 mr-2" />
          恢复默认值
        </Button>
      </div>

      <FactorRuleEditor
        title="跨越档距系数"
        category="spanFactorRules"
        rules={currentFactors.spanFactorRules}
        description="根据跨越档距长度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越高度系数"
        category="heightFactorRules"
        rules={currentFactors.heightFactorRules}
        description="根据跨越高度确定施工难度系数"
      />

      <FactorRuleEditor
        title="封网长度系数"
        category="nettingFactorRules"
        rules={currentFactors.nettingFactorRules}
        description="根据封网长度确定材料用量系数"
      />

      <FactorRuleEditor
        title="交叉角度系数"
        category="angleFactorRules"
        rules={currentFactors.angleFactorRules}
        description="根据与被跨越物的交叉角度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越宽度系数"
        category="widthFactorRules"
        rules={currentFactors.widthFactorRules}
        description="根据被跨越物宽度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越类型系数"
        category="typeFactorMultipliers"
        rules={currentFactors.typeFactorMultipliers}
        isTypeRule={true}
        description="根据不同的跨越类型确定基础系数"
      />
    </div>
  );
};

export default EngineeringFactors;
